package pers.walker.recorduser.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jwt.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import pers.walker.recorduser.entity.User;
import pers.walker.recorduser.mapper.UserMapper;
import pers.walker.recorduser.service.UserService;
import util.Result;

import java.util.HashMap;
import java.util.Objects;

@RestController
@Api(tags = "用户接口")
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;

    @ApiOperation(value = "登录接口")
    @PostMapping("/login")
    public Result<String> login(@RequestBody User user) {
        if (StrUtil.isBlank(user.getUsername())) {
            return Result.fail("用户名 username 不可为空");
        }
        User databaseUser = userService.getByUsername(user.getUsername());
        if (Objects.isNull(databaseUser)) {
            return Result.fail("用户名或密码错误");
        }
        if (Objects.equals(user.getPassword(), databaseUser.getPassword())) {
            HashMap<String, String> map = new HashMap<>();
            map.put("username", user.getUsername());
            return Result.success(JwtTokenUtil.getToken(map));
        } else {
            return Result.fail("密码错误");
        }
    }

    @ApiOperation(value = "测试接口")
    @GetMapping("/test")
    public String test() {

        log.info("用户访问成功");

        return "200";
    }

    @ApiOperation(value = "注册接口")
    @PostMapping("/register")
    public Result<User> register(@RequestBody User user) {
        if (StrUtil.isBlank(user.getId())) {
            user.setId(IdUtil.simpleUUID());
        }
        boolean saveOrUpdateFlag = userService.saveOrUpdate(user);
        if (saveOrUpdateFlag) {
            return Result.success();
        }
        return Result.fail();
    }
    @ApiOperation("查询列表")
    @PostMapping("/queryList/{current}/{size}")
    public Result<IPage<User>> queryList(@RequestBody User user, @PathVariable long current, @PathVariable long size) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        IPage<User> page = new Page<>(current, size);
        IPage<User> userIPage = userMapper.selectPage(page, queryWrapper);
        return Result.success(userIPage);
    }
}
